#include <iostream>
#include <queue>

#include "CandidateResult.h"
#include "EditDistance.h"
#include "EnDictionary.h"
#include "Recommender.h"

using std::priority_queue;

string toLower(const string& str) {
    string ret = str;
    for (auto& ch : ret) {
        if (isupper(ch)) {
            ch = tolower(ch);
        }
    }
    return ret;
}

string EnRecommender::recommender(const string& queryString) {
    EnDictionary dict;  // 每次推荐词都会在构建词典时读取磁盘
    vector<pair<string, int>> queryRes(std::move(dict.doQuery(queryString)));
    if (queryRes.size() == 0) {
        return "";
    }
    // 构建优先级队列
    string cmpString = toLower(queryString);
    priority_queue<CandidateResult, vector<CandidateResult>, BetterCandidate>
        candis;
    for (auto& elem : queryRes) {
        int distance = editDistance(cmpString, elem.first);
        candis.emplace(elem.first, elem.second, distance);
    }
    // 遍历完成后优先级队列里保存的是有序的关键字
    vector<string> ret;
    for (int i = 0; i < 5; ++i) {
        CandidateResult top = candis.top();
        ret.push_back(top._word);
        candis.pop();
    }
    json retJson;
    retJson["Keywords"] = ret;
    return retJson.dump();
}